//显示最快成绩和平均成绩

package edu.nuc.rubikrecord;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.TextView;
import edu.nuc.SQLoperation.SQLConstant;
import edu.nuc.SQLoperation.SQLiteHelper;
import edu.nuc.rubikstopwatch.R;
import edu.nuc.rubikstopwatch.Rubik;

public class StatsRecord extends Activity {
	private static List<Rubik> rubiks;
	private String fastest;
	private String average;
	SQLiteHelper DBHelper = null;

	private TextView fastestView = null;
	private TextView averageView = null;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (DBHelper != null) {
			DBHelper.close();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.statsrecord);

		fastestView = (TextView) findViewById(R.id.fastestRecordTextViewID);
		averageView = (TextView) findViewById(R.id.averageRecordTextViewID);

		// 查询统计显示
		StatsRecord stats = new StatsRecord();
		stats.fetchRubik(getApplicationContext(), 0);
		fastestView.setText(stats.getFastest());
		averageView.setText(stats.getAverage());
	}

	// 按照millisScore升序取出数据
	public Cursor getDb(Context context, long selection) {
		DBHelper = new SQLiteHelper(context, SQLConstant.DB_NAME, null, 1);
		if (selection == 0) {
			Cursor cursor = DBHelper.query("_millisScore asc");
			return cursor;
		} else {
			Cursor cursor = DBHelper.limitQuery("_millisData >" + selection,
					"_millisScore asc");
			startManagingCursor(cursor);
			return cursor;
		}
	}

	// 从数据库取出数据
	// 将数据转化为Rubik类型，并添加到rubiks中
	public void fetchRubik(Context context, long selection) {
		if (rubiks == null) {
			rubiks = new ArrayList<Rubik>();
		} else {
			rubiks.clear();
		}
		Cursor c = getDb(context, selection);
		startManagingCursor(c);
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					Rubik rubik = Rubik.parseCursor(c);
					rubiks.add(rubik);
				} while (c.moveToNext());
			}
		}
		c.close();
		DBHelper.close();
	}

	// 得到最快成绩
	// list的第一个
	public String getFastest() {
		if (rubiks != null && rubiks.size() != 0) {
			Rubik rubik = rubiks.get(0);
			fastest = rubik.record;
			return fastest;
		} else {
			return "no record";
		}
	}

	// Get a Average
	public String getAverage() {
		long sum = 0;
		long ave = 0;
		Rubik rubik = new Rubik();
		if (rubiks != null && rubiks.size() != 0) {
			for (int i = 0; i < rubiks.size(); i++) {
				rubik = rubiks.get(i);
				sum = sum + rubik.millisRecord;
			}
			ave = sum / rubiks.size();
			average = rubik.parseMillistime(ave);
			return average;
		} else {
			return "no record";
		}
	}

}
